package com.farm.controller;

import com.farm.domain.*;
import com.farm.service.ProduceService;
import com.farm.service.AccountService;
import com.farm.utils.Result;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/produce")
@AllArgsConstructor
public class ProduceController {

    ProduceService produceService;
    AccountService accountService;

    /**
     * 获取所有商品信息
     */
    @GetMapping("/getProduceList")
    public Result getAllProduce(Integer pageNum, Integer pageSize, String produceType, String produceName) {

        log.info("商品查询信息中....");
        Result result = new Result();
        JSONArray records = null;

        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }

        if (produceType != null && !produceType.equals("")) {
            log.info("查询分类商品信息....");
            records = produceService.getProduceChooseType(pageNum, pageSize, produceType);
        } else if (produceName != null && !produceName.equals("")) {
            log.info("搜索商品信息....");
            records = produceService.searchProduce(pageNum, pageSize, produceName);
        } else {
            log.info("查询所有商品信息....");
            records = produceService.getAllProduce(pageNum, pageSize);
        }
        if (records.size() > 0) {
            log.info("查询成功！");
            result.setMsg("已为您查询商品信息!");
            result.setData(records);
        } else if (records.size() == 0) {
            log.info("查询成功！暂无商品信息！");
            result.setCode(230);
            result.setMsg("暂无商品信息！");
        } else {
            log.info("查询失败！");
            result.setCode(500);
            result.setMsg("商品信息查询失败！");
        }

        return result;
    }


    @PostMapping("/uploadImg")
    public Result uploadProduceImg(ServletRequest servletRequest, MultipartHttpServletRequest files) {
        Result result = new Result();
        String path = "G:\\Documents\\GraduationProject\\wisdom-farm-ssm\\src\\main\\resources\\static\\assest\\img\\produceImg";
        String uuid = files.getParameter("uuid");
        if (uuid.equals("")) {
            result.setCode(500);
            result.setMsg("由于未知因素，图片上传失败！");
        }

        MultiValueMap<String, MultipartFile> multiFileMap = files.getMultiFileMap();
        List<MultipartFile> filesList = multiFileMap.get("file");

        int filesLength = filesList.size();
        int filesSuccessFlag = 0;                                               //保存图片成功标志位

        for (MultipartFile file : filesList) {
            String fileName = file.getOriginalFilename();                   //获取上传的文件名称
            int suffixTemp = fileName.lastIndexOf(".");
            Date date = new Date();
            long timeSleep = date.getTime();

            try {
                String suffixName = fileName.substring(suffixTemp);                //获取文件后缀名
                if (!suffixName.equals(".jpg")) {
                    if (!suffixName.equals(".jpeg")) {
                        if (!suffixName.equals(".png")) {
                            continue;
                        }
                    }
                }
                fileName = uuid + "_" + timeSleep + suffixName;        //生成新的文件名称
                File targetFile = new File(path);
                File saveFile = new File(targetFile, fileName);
                file.transferTo(saveFile);
                log.info("商家商品图片资源保存本地成功....");

                String img = "/img/produceImg/" + fileName;
                ProduceImg produceImg = new ProduceImg();
                produceImg.setProduceID(uuid);
                produceImg.setImg(img);
                Integer res = produceService.imsertProduceImg(produceImg);

                if (res == 1) {
                    filesSuccessFlag += 1;
                } else {
                    boolean delete = saveFile.delete();
                    if (delete) {
                        log.info("图片资源信息同步数据库出错！本地图片资源已删除！");
                    } else {
                        log.info("图片资源信息同步数据库出错！本地图片资源删除失败！");
                    }
                }

            } catch (Exception e) {
                continue;
            }
        }

        if (filesLength == filesSuccessFlag) {
            result.setMsg("图片全部上传成功！");
        } else if (filesSuccessFlag == 0) {
            result.setCode(500);
            result.setMsg("图片上传失败！");
        } else {
            result.setCode(521);
            result.setMsg("部分图片由于未知因素上传失败！");
        }
        return result;
    }

    /**
     * 删除商品信息
     *
     * @param params 请求集
     */

    @PostMapping("/deleteProduce")
    public Result deleteProduce(@RequestBody Map params) {
        log.info("删除商品信息中！");
        Result result = new Result();
        String uuid = (String) params.get("uuid");
        Integer res = produceService.deleteProduce(uuid);
        if (res == 1) {
            result.setMsg("删除商品信息成功！");
        } else {
            result.setCode(500);
            result.setMsg("删除商品信息失败！");
        }
        return result;
    }

    /**
     * 删除商品图片
     *
     * @param params 请求参数组
     */

    @PostMapping("/deleteImg")
    public Result deleteImg(@RequestBody Map params) {
        log.info("图片资源删除中...");
        Result result = new Result();
        String path = "G:\\Documents\\GraduationProject\\wisdom-farm-ssm\\src\\main\\resources\\static\\assest\\img\\produceImg";
        String fileName = (String) params.get("fileName");

        File targetFile = new File(path);
        File deleteFile = new File(targetFile, fileName);

        boolean deleteFlag = deleteFile.delete();
        if (deleteFlag) {
            log.info("图片资源删除成功！");
            Integer res = produceService.deleteImg(fileName);
            int count = 0;
            while (res != 1 && count < 5) {
                res = produceService.deleteImg(fileName);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    log.info("系统休眠异常");
                }
            }
            if (res == 1) {
                log.info("商品图片删除同步数据库成功");
                result.setMsg("图片删除成功！");
            } else {
                log.info("商品图片删除同步数据库失败");
                result.setCode(500);
                result.setMsg("图片删除失败！");
            }
        } else {
            log.info("图片资源删除失败！");
            result.setCode(500);
            result.setMsg("图片删除失败！");
        }

        return result;
    }

    /**
     * 添加商品信息
     *
     * @param servletRequest 请求信息
     * @param params         商品参数信息集合
     */

    @PostMapping("/addProduce")
    public Result insertProduce(ServletRequest servletRequest, @RequestBody Map params) {
        Result result = new Result();
        log.info("商户添加商品");

        String loginName = (String) servletRequest.getAttribute("loginName");
        Account account = accountService.getAll(loginName);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();


        String uuid = UUID.randomUUID().toString().replace("-", ""); //生成uuid编码
        String name = (String) params.get("produceName");
        String price = (String) params.get("price");
        String describe = (String) params.get("describe");
        String produceType = (String) params.get("produceType");
        String count = (String) params.get("count");
        String collectionDate = simpleDateFormat.format(date);


        Produce produce = new Produce();
        produce.setProduceID(uuid);
        produce.setName(name);
        produce.setPrice(price);
        produce.setCount(count);
        produce.setDescribe(describe);
        produce.setMerchantID(account.getId());
        produce.setFarmStatus(account.getStatus());
        produce.setProduceType(produceType);
        produce.setCollectionDate(collectionDate);

        Integer res = produceService.addProduce(produce);

        if (res == 1) {
            log.info("商户添加成功");
            result.setMsg("添加商品成功！");
            HashMap map = new HashMap();
            map.put("produceID", uuid);
            result.setData(map);
        } else {
            log.info("商户添加失败");
            result.setMsg("添加商品失败！");
        }
        return result;
    }

    /**
     * 查询指定商家所有商品信息
     *
     * @param servletRequest
     * @return
     */

    @GetMapping("/getMerchantProduce")
    public Result getMerchantProduce(ServletRequest servletRequest) {
        log.info("商家查询商品信息");

        Result result = new Result();
        String loginName = (String) servletRequest.getAttribute("loginName");
        Account account = accountService.getAll(loginName);

        List<Produce> produceList = produceService.getMerchantProduce(account.getId());
        if (produceList.size() == 0 || produceList == null) {
            log.info("商家商品信息为空！");
            result.setCode(200);
            result.setMsg("农场农产品信息为空！");
            return result;
        }

        JSONArray records = produceService.getMerchantProduceImg(produceList);

        if (records != null && records.size() > 0) {
            log.info("商品信息查询完毕");
            HashMap map = new HashMap();
            map.put("total", records.size());
            map.put("data", records);
            result.setMsg("查询商品信息成功！");
            result.setData(map);
        } else {
            log.info("商家商品信息为空！");
            result.setCode(200);
            result.setMsg("商品信息为空！");
        }

        return result;
    }

    /**
     * 获取商品信息详情
     */

    @PostMapping("/getProduceDetail")
    public Result getProduceDetail(@RequestBody Map params) {
        Result result = new Result();
        String uuid = (String) params.get("uuid");

        JSONArray details = produceService.getProduceDetail(uuid);
        if (details != null) {
            result.setMsg("商品信息查询成功！");
            result.setData(details);
        } else {
            result.setCode(500);
            result.setMsg("商品信息查询失败！");
        }
        return result;

    }

    /**
     * 更新商品信息详情
     *
     * @param params
     */

    @PostMapping("/updateProduceDetail")
    public Result updateProduceDetail(@RequestBody Map params) {
        log.info("商品信息更新中....");
        Result result = new Result();

        String uuid = (String) params.get("uuid");
        String name = (String) params.get("produceName");
        String price = (String) params.get("price");
        String describe = (String) params.get("describe");
        String produceType = (String) params.get("produceType");
        String count = (String) params.get("count");

        Integer res = produceService.updateProduceDetail(uuid, name, price, describe, produceType, count);

        if (res == 1) {
            log.info("商品信息同步数据库成功！");
            result.setMsg("商品信息更新成功！");
        } else {
            log.info("商品信息同步数据库失败！");
            result.setCode(500);
            result.setMsg("商品信息更新失败！");

        }
        return result;
    }

    /**
     * 添加商品生长信息
     */

    @PostMapping("/addProduceGrowUp")
    public Result addProduceGrowup(@RequestBody Map params) {
        log.info("商户添加商品生长信息中.....");
        Result result = new Result();

        Integer integer = produceService.addProduceGrowup(params);
        if (integer == 1) {
            log.info("添加成功！");
            result.setMsg("添加生长信息状况成功！");
        } else {
            log.info("添加失败！");
            result.setCode(500);
            result.setMsg("添加生长信息状况失败！");
        }

        return result;
    }

    /**
     * 查询商品生长信息
     *
     * @param params 请求数据集
     */
    @PostMapping("/getProduceGrowUp")
    public Result getProduceGrowUp(@RequestBody Map params) {
        log.info("商户查询商品生长信息中.....");
        Result result = new Result();

        List<ProduceGrowUp> list = produceService.getProduceGrowUp(params);
        if (list.size() > 0) {
            log.info("查询成功！");
            result.setMsg("查询商品生长信息成功！");
            if (list.size() == 1) {
                result.setData(list.get(0));
            } else {
                result.setData(list);
            }

        } else if (list.size() == 0) {
            log.info("暂无商品生长状况信息");
            result.setCode(233);
            result.setMsg("暂无商品生长状况信息！");
        } else {
            log.info("查询失败！");
            result.setCode(500);
            result.setMsg("查询商品生长信息成功！");
        }

        return result;
    }


    /**
     * 查询商品种类表
     */

    @GetMapping("/getProduceType")
    public Result getProduceType() {
        Result result = new Result();

        List<ProduceType> types = produceService.getProduceType();
        if (types.size() > 0) {
            result.setMsg("查询商品种类成功！");
            result.setData(types);
        } else if (types.size() == 0) {
            result.setCode(233);
            result.setMsg("暂无商品种类信息！");
        } else {
            result.setCode(500);
            result.setMsg("查询商品种类信息失败！");
        }
        return result;
    }

}
